/*
 * BootApp.cpp
 *
 *  Created on: 2020年7月22日
 *      Author: terry
 */

#include "BootApp.h"
#include "Path.h"

#ifdef WIN32
    //
#else
    #include <unistd.h>
#endif //

BootApp::BootApp()
{
}

BootApp::~BootApp()
{
}

const char* BootApp::getAppName()
{
#ifdef WIN32
    return "BootApp.bat";
#else
    return "BootApp.sh";
#endif //
}

bool BootApp::exist(const std::string& dirpath)
{
    std::string workdir = dirpath;
    if (workdir.empty())
    {
        workdir = comn::Path::getWorkDir();
    }
    std::string filepath = comn::Path::join(workdir, getAppName());
    return comn::Path::exist(filepath);
}


#ifdef WIN32

bool BootApp::run(const std::string& dirpath)
{
    std::string filepath = comn::Path::join(dirpath, getAppName());

    STARTUPINFO si;
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    si.wShowWindow = SW_HIDE;

    PROCESS_INFORMATION pinfo;
    memset(&pinfo, 0, sizeof(pinfo));

    DWORD dwCreationFlags = 0;
    BOOL ret = CreateProcessA(NULL, (LPSTR)filepath.c_str(),
        NULL, NULL,
        FALSE, dwCreationFlags, NULL, dirpath.c_str(), &si,
        &pinfo);

    CloseHandle(pinfo.hProcess);
    CloseHandle(pinfo.hThread);

    return ret == TRUE;
}

#else

bool BootApp::run(const std::string& dirpath)
{
    std::string filepath = comn::Path::join(dirpath, getAppName());
    char* argv[] = { 0 };
    int ret = execv(filepath.c_str(), argv);
    return ret != -1;
}


#endif //